package com.papper.common.enums.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.TreeMap;

/**
 * 通用方法工具类
 *
 * @author 小懒虫
 * @date 2018/10/15
 */
public class EnumsUtil {
    /**
     * 将枚举转成List集合
     *
     * @param enumClass 枚举类
     */
    public static Map<Long, String> enumToMap(Class<?> enumClass) {
        Map<Long, String> map = new TreeMap<>();
        try {
            Object[] objects    = enumClass.getEnumConstants();
            Method   getCode    = enumClass.getMethod("getCode");
            Method   getMessage = enumClass.getMethod("getMessage");
            for (Object obj : objects) {
                Object iCode    = getCode.invoke(obj);
                Object iMessage = getMessage.invoke(obj);
                map.put(Long.valueOf(String.valueOf(iCode)), String.valueOf(iMessage));
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
        }
        return map;
    }

    /**
     * 根据枚举code获取枚举对象
     *
     * @param enumClass 枚举类
     * @param code      code值
     */
    public static Object enumCode(Class<?> enumClass, Object code) {
        try {
            Object[] objects = enumClass.getEnumConstants();
            Method   getCode = enumClass.getMethod("getCode");
            for (Object obj : objects) {
                Object iCode = getCode.invoke(obj);
                if (iCode.equals(code)) {
                    return obj;
                }
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        }
        return "";
    }
}
